package com.woniu.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 获取视频时长
 */
public class getVideoDuration {
    public static String getVideoDurationFormatted(String videoPath) {
        try {
            FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(videoPath);
            grabber.start();
            long duration = grabber.getLengthInTime() / 1000_000; // 微秒转为秒
            grabber.stop();

            double minutes = (double) duration / 60;
            return String.format("%.2f", minutes);

        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }
    }
    /**
     * 获取视频大小（字节数）
     */
    public static long getVideoSize(String videoPath) {
        try {
            URL url = new URL(videoPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 先尝试 HEAD 请求
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();

            long length = connection.getContentLengthLong();
            if (length > 0) {
                connection.disconnect();
                return length;
            }

            // 如果 HEAD 失败，尝试 GET 并立即断开连接
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Range", "bytes=0-1"); // 只请求前两个字节
            connection.connect();

            if (connection.getResponseCode() >= 400) {
                System.err.println("HTTP 错误码：" + connection.getResponseCode());
                connection.disconnect();
                return -1;
            }

            String contentRange = connection.getHeaderField("Content-Range");
            if (contentRange != null && contentRange.startsWith("bytes")) {
                // 格式：bytes 0-1/123456789
                String[] parts = contentRange.split("/");
                if (parts.length == 2) {
                    length = Long.parseLong(parts[1]);
                    connection.disconnect();
                    return length;
                }
            }

            length = connection.getContentLengthLong();
            connection.disconnect();
            return length;

        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    /**
     * 格式化文件大小为易读字符串
     */
    public static String formatFileSize(long bytes) {
        if (bytes < 0) return "未知大小";
        double mb = bytes / (1024.0 * 1024.0);
        return String.format("%.2f MB", mb);
    }
}


